/*
Section: Alternative treatment definitions
Content: Table G.5
Paper: "Immigrants Return Intentions and Labor Market Behavior when the Home Country is Unsafe"
Journal: Journal of Labor Economics
Authors: Jacopo Bassetto, Teresa Freitas-Monteiro
*/


********************************************************************************
**# LOAD ANALYSIS DATASET
********************************************************************************

use "$intermediate/finaldata_main_ieb_noevent.dta", clear

tab year 
cap drop _merge

* MERGE THE NEW TREATMENT VARIABLES
merge m:1 ieb_nat_id startmy using "$globalterror/final\prepost_extra_startdates.dta", keep(1 3) 


*** Run faster

keep if match_date != .
drop if year==.
keep if inrange(year,2000,2018)
keep if !inlist(ieb_nat_id,.,0)


g ysm_v2= int((endepi-entry_spell)/365)

rename ysm_atunemp ysm_old
rename ysm_v2 ysm_atunemp
label var ysm_atunemp "Years since mig."


cap drop allcontrols
g allcontrols=1 if  unemp_3m!=. & edu_max!=. & age !=. & frau!=. & ysm_atunemp!=. & ln_wage_any_lb!=. & ln_firmsize!=.  & state!=. & woao_llm!=.
keep if allcontrols==1


**************************************************************
**# GENERATE ALTERNATIVE TREATMENT VARIABLES  

	* 1) BASIC: WITHIN TREATED MONTH, CONSIDER ONLY PEOPLE WHO ENTER UNEMP BEFORE 1ST ATTACK
	
	rename treatment_firstaatck treatment_firstattack
	cap drop treat_firstattack
	g  treat_firstattack   = treatment_firstattack 
	replace treat_firstattack = . if endepi > firstattack_date

	gen dist_event = firstattack_date - endepi		// firstattack_date varies between treated and controls
	

	* 2) SPANNING MONTHS: CONSIDER ONLY PEOPLE WHO ENTER UNEMP X DAYS BEFORE 1ST ATTACK, THIS CAN BE IN TREATED MONTH OR THE MONTH BEFORE
	
	foreach i in 5 10 15 20 {
		
		g treat`i'd = treatment_terror_firstattack_`i'd
		
		replace treat`i'd = . if endepi > firstattack_date & endepi!=. & firstattack_date !=. // after first attack
		replace treat`i'd = . if endepi < firstattack_`i'd_date  & endepi!=. & firstattack_date !=. // before the first date to consider
		
		gen dist`i' = firstattack_`i'd_date	 - endepi

	}
	
	
	* 3) SAMPLE RESTRICTION BASED
	
		cap drop dist_event
		gen dist_event = firstattack_date - endepi

		tab dist_event if treat_firstattack !=. & dist_event < 0 &  register_unemp==1
	
		cap drop restrict_preterror
		gen restrict_preterror = 1 if inrange(dist_event,-40,-16) & treatment_terror_m3y_p90 == 1
		replace restrict_preterror = 0 if restrict_preterror !=1
		
		format startdate %td
	
	
	* 4) ALTERNATIVE TREATMENT INDICATORS
	
	g treat_month=1 if treat_firstattack== 1 
	replace treat_month = 0 if treatment_terror_m3y_p90 == 0 
	
	foreach i in 15 {
		
      cap drop treat`i'd_t
		g treat`i'd_t = 1 if treat`i'd == 1 
		replace treat`i'd_t = 0 if treatment_terror_m3y_p90 == 0 

	}
	
		
		
		** Ensure there is ppl in control and treated within the same year and state (for each treatment)
			cap drop year2 month2
			g year2=year(dofm(event_startmy))
			g month2=month(dofm(event_startmy))

			cap drop k*
		 
			local varlist treatment_terror_m3y_p90 treat_month treat1*d treat1*d_t
			
				foreach x of varlist `varlist'  {
					
				
				* CREATE DATE VARIABLES
				cap drop date2
				g date2 = event_startmy
				
				* CREATE INDICATOR TO INCLUDE ONLY PERIODS WITH AT LEAST ONE CONTROL AND ONE TREATED  
				
				cap drop max_`x' min_`x'
				bysort ieb_nat date2 state: egen max_`x'=max(`x')
				bysort ieb_nat date2 state: egen min_`x'=min(`x')
				cap drop k_`x'_st
				g k_`x'_st=1 if max_`x'==1 & min_`x'==0
				cap drop max_`x' min_`x'
					
					}
			
		
		** Outcomes	

		replace register_unemp = 0 if match_date != . & register_unemp != 1 
		
			foreach x in 30 92  {
			gen register_`x'm = 1 if dist_alo_emp <= `x' 
			replace register_`x'm = 0 if dist_alo_emp > `x' 
			 
			}
		cap drop register_1m register_3m
		rename register_30m register_1m
		rename register_92m register_3m

		label var register_1m "Register within 1m"
		label var register_3m "Register within 3m"

		
		
		** Other controls
		cap drop semester quarter
		g semester=0 if inrange(month,1,6)
			replace semester=1 if inrange(month,2,12)
			g quarter=0 if inrange(month,1,3)
			replace quarter=1 if inrange(month,4,6)
			replace quarter=2 if inrange(month,7,9)
			replace quarter=3 if inrange(month,10,12)
	
			
		** Cluster for standard errors

			clonevar relevantterror_m3y_p90=startmy if treatment_terror_m3y_p90==1
			replace relevantterror_m3y_p90=startmy+3 if treatment_terror_m3y_p90==0

			egen clusterterror_m3y_p90=group(relevantterror_m3y_p90)



	save "$final/finaldata_firstdates_light_final.dta", replace
	
********************************************************************************
**# Table G.5, Panel A, Column 3,4				
********************************************************************************
eststo clear
local i=1
foreach out in  unemp_1m unemp_3m  {
global control_ext = "i.edu_max age frau c.ysm_atunemp##c.ysm_atunemp ln_wage_any_lb ln_firmsize full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb"

qui eststo Amod`i': reghdfe `out' treatment_terror_m3y_p90 $control_ext if  k_treatment_terror_m3y_p90_st==1 & register_unemp==1 & restrict_preterror != 1, absorb(i.ieb_nat_id#i.year2 i.year2#i.month i.state)  vce(cluster clusterterror_m3y_p90)

sum	 `out' if k_treatment_terror_m3y_p90_st==1 & register_unemp==1 & treatment_terror_m3y_p90 == 0 & restrict_preterror != 1
estadd scalar ymean = r(mean)
estadd local yearorigin "Yes"
estadd local yearmonth "Yes"
estadd local state "Yes"
estadd local control "Yes"
estadd local control_ext "Yes"

local i=`i'+1
	}


********************************************************************************
**# Table G.5, Panel B, Column 1,2			
********************************************************************************
local i=1
foreach out in  unemp_1m unemp_3m  {
global control_ext = "i.edu_max age frau c.ysm_atunemp##c.ysm_atunemp ln_wage_any_lb ln_firmsize full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb"

qui eststo Bmod`i': reghdfe `out' treat_month $control_ext if  k_treat_firstattack_st==1 & register_unemp==1 & dist_event != 0, absorb(i.ieb_nat_id#i.year2 i.year2#i.month i.state)  vce(cluster cluster)

sum `out' if e(sample) == 1 & treat_month == 0
estadd scalar ymean = r(mean)
estadd local yearorigin "Yes"
estadd local yearmonth "Yes"
estadd local state "Yes"
estadd local control "Yes"
estadd local control_ext "Yes"


local i=`i'+1
}

		
********************************************************************************
**# Table G.5, Panel B, Column 3,4			
********************************************************************************


local i=1
foreach out in unemp_1m unemp_3m  {
	global control_ext = "i.edu_max age frau c.ysm_atunemp##c.ysm_atunemp ln_wage_any_lb ln_firmsize full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb"
qui eststo Cmod`i': reghdfe `out' treat15d_t $control_ext if  k_treat15d_t_st==1 & register_unemp==1, absorb(i.ieb_nat_id#i.year2 i.year2#i.month i.state)  vce(cluster cluster)

sum `out' if e(sample) == 1 & treat15d_t == 0
estadd scalar ymean = r(mean)
estadd local yearorigin "Yes"
estadd local yearmonth "Yes"
estadd local state "Yes"
estadd local control "Yes"
estadd local control_ext "Yes"


local i=`i'+1
	}

esttab Amod* using "$table/iebprepost_alttreat_final.tex", star(* 0.10 ** 0.05 *** 0.01) se append b(3) drop(*edu_max age frau *ysm_atunemp ln_wage_any_lb ln_firmsize_lb full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb _cons) nocons nogaps nonotes noobs nomtitle ///
varlabel(treatment_terror_m3y_p90 "Post-Terror") ///
mgroups("\shortstack{Unemp. in month with terror event\\-15/+15d before/after 1st attack}", pattern(1 0)   prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
mtitles("\shortstack{Emp. within\\1m}" "\shortstack{Emp. within\\3m}") ///
fragment scalars("nobs Observations" "ymean Mean outcome") ///
sfmt(%9.0fc %9.3f)  prehead(" \def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \begin{tabular}{l*{5}{c}} \hline\hline")



esttab Bmod* Cmod* using "$table/iebprepost_alttreat_final.tex", star(* 0.10 ** 0.05 *** 0.01) se append b(3) drop(*edu_max age frau *ysm_atunemp ln_wage_any_lb ln_firmsize_lb full_time_lb share_for_lb_ab_med qualif_hq_lb_ab_med abovemedian_AKM_lb _cons) nocons nogaps nonotes noobs nomtitle ///
mgroups("\shortstack{Unemp. in month with terror\\event before 1st attack}" "\shortstack{Unemp. in month with terror\\event before 1st attack\\+ 15d prior month}", pattern(1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
varlabel(treat_month "Post-Terror" treat15d_t "Post-Terror") ///
mtitles("\shortstack{Emp. within\\1m}" "\shortstack{Emp. within\\3m}") ///
scalars("nobs Observations" "ymean Mean outcome" "yearorigin Origin country x Year FE" "yearmonth Month FE x Year FE" "state State of Residency FE" "control Individual Controls" "control_ext Extended Controls") ///
sfmt(%9.0fc %9.3f %1s %1s %1s %1s %1s) ///
fragment postfoot("\hline\hline \\ \end{tabular}")


	
	
	